<template>
  <div class="app-container">
    <el-form
      :model="spu"
      :rules="rules"
      ref="form"
      label-position="right"
      label-width="100px"
      style="margin-top: 20px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item prop="name">
            <span slot="label">商品名称</span>
            <el-input v-model="spu.name" maxlength="200" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <span slot="label">副标题</span>
            <el-input v-model="spu.subtitle" maxlength="200" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="name">
            <span slot="label">零售价</span>
            <el-input v-model="spu.price" maxlength="200" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <span slot="label">抵扣价</span>
            <el-input v-model="spu.offsettingPrice" maxlength="200" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="name">
            <span slot="label">进货价</span>
            <el-input v-model="spu.purchasePrice" maxlength="200" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="logisticsTemplateId" v-if="spu.isVirtual != '1'">
            <span slot="label">物流模板</span>
            <el-select
              v-model="spu.logisticsTemplateId"
              filterable
              placeholder="请选择物流模板"
              style="width: 100%"
            >
              <el-option
                v-for="item in logisticsTemplates"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <router-link
              :to="{ path: '/order/delevierManager/OmsLogisticsTemplate' }"
            >
              <el-link type="primary">立即去设置</el-link>
            </router-link>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="name">
            <span slot="label">预估收益</span>
            <el-input v-model="spu.estimatedRevenue" maxlength="200" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="服务支持">
        <el-checkbox-group v-model="serviceSupportChecked">
          <el-checkbox
            v-for="serviceSupport in serviceSupports"
            :label="serviceSupport.id"
            :key="serviceSupport.id"
          >
            {{ serviceSupport.name }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="是否虚拟商品">
        <el-switch
          style="vertical-align: sub"
          v-model="spu.isVirtual"
          active-value="1"
          inactive-value="0"
          active-color="#13ce66"
          inactive-color="#ff4949"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="是否上架">
        <el-switch
          style="vertical-align: sub"
          v-model="spu.shelvesStatus"
          active-value="1"
          inactive-value="0"
          active-color="#13ce66"
          inactive-color="#ff4949"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="商品状态">
        <el-radio v-model="spu.goodsStatus" label="0">口碑好货</el-radio>
        <el-radio v-model="spu.goodsStatus" label="1">新品扫雷</el-radio>
      </el-form-item>
      <el-form-item label="已售">
        <el-row>
          <el-col :span="3">
            <span>真实已售</span>
            <span>{{ spu.goodsRealSold }}</span>
          </el-col>
          <el-col :span="8">
            <span>修改已售</span>
            <el-input
              v-model="spu.goodsSold"
              maxlength="200"
              style="width: 160px;"
            />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="好评率">
        <el-row>
          <el-col :span="3">
            <span>真实好评率</span>
            <span>{{ spu.approvalRealRating }}</span>
          </el-col>
          <el-col :span="8">
            <span>修改好评率</span>
            <el-input
              v-model="spu.approvalRating"
              maxlength="200"
              style="width: 160px;"
            />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="评价标签">
        <el-input
          v-model="spu.evaluationFlag[0]"
          maxlength="200"
          style="width: 160px;"
        />
        <el-input
          v-model="spu.evaluationFlag[1]"
          maxlength="200"
          style="width: 160px;"
        />
        <el-input
          v-model="spu.evaluationFlag[2]"
          maxlength="200"
          style="width: 160px;"
        />
        <el-input
          v-model="spu.evaluationFlag[3]"
          maxlength="200"
          style="width: 160px;"
        />
        <el-input
          v-model="spu.evaluationFlag[4]"
          maxlength="200"
          style="width: 160px;"
        />
      </el-form-item>
      <el-form-item prop="url">
        <span slot="label">主图</span>
        <el-upload
          style="display: inline-block"
          accept=",.JPG,.jpeg,.png,.gif,.ico,.JPEG,.PNG,.GIF,.ICO,.jpg"
          :action="uploadApi"
          list-type="picture-card"
          :headers="headers"
          name="image"
          :file-list="spu.url"
          :on-preview="handlePictureCardPreview"
          :on-remove="removeSpuPic1"
          :on-success="uploadSpuPicSuccess1"
        >
          <el-tooltip
            effect="dark"
            content="建议图片尺寸800px * 800px"
            placement="right"
          >
            <i class="el-icon-plus"></i>
          </el-tooltip>
        </el-upload>
        <el-dialog :visible.sync="imageDialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item prop="topUrl">
        <span slot="label">顶部图</span>
        <el-upload
          style="display: inline-block"
          accept=",.JPG,.jpeg,.png,.gif,.ico,.JPEG,.PNG,.GIF,.ICO,.jpg"
          :action="uploadApi"
          list-type="picture-card"
          :headers="headers"
          name="image"
          :file-list="spu.topUrl"
          :on-preview="handlePictureCardPreview"
          :on-remove="removeSpuPic2"
          :on-success="uploadSpuPicSuccess2"
        >
          <el-tooltip
            effect="dark"
            content="建议图片尺寸800px * 800px"
            placement="right"
          >
            <i class="el-icon-plus"></i>
          </el-tooltip>
        </el-upload>
        <el-dialog :visible.sync="imageDialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item prop="detailsUrl">
        <span slot="label">详情页图</span>
        <el-upload
          style="display: inline-block"
          accept=",.JPG,.jpeg,.png,.gif,.ico,.JPEG,.PNG,.GIF,.ICO,.jpg"
          :action="uploadApi"
          list-type="picture-card"
          :headers="headers"
          name="image"
          :file-list="spu.detailsUrl"
          :on-preview="handlePictureCardPreview"
          :on-remove="removeSpuPic3"
          :on-success="uploadSpuPicSuccess3"
        >
          <el-tooltip
            effect="dark"
            content="建议图片尺寸800px * 800px"
            placement="right"
          >
            <i class="el-icon-plus"></i>
          </el-tooltip>
        </el-upload>
        <el-dialog :visible.sync="imageDialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="介绍视频">
        <el-upload
          class="upload-demo"
          accept=".mp4"
          name="video"
          :action="uploadVideoApi"
          :file-list="videos"
          :headers="headers"
          :before-upload="videoBeforeUpload"
          :on-remove="removeVideo"
          :on-success="uploadVideoSuccess"
        >
          <el-button size="small" type="primary">点击上传视频</el-button>
          <div slot="tip" class="el-upload__tip">
            建议上传mp4(H.264编码)文件，且不超过10M
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item v-if="$route.query.id">
        <span slot="label">规格</span>
        <div style="display: flex; justify-content: space-between">
          <el-button
            type="primary"
            @click="(skuTableDialog = true), (skuType = 'add')"
            >新增规格</el-button
          >
        </div>
        <el-table
          style="margin-top: 10px"
          :data="skuData"
          border
          fit
          highlight-current-row
        >
          <el-table-column label="型号" width="110">
            <template slot-scope="scope">
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column label="颜色" width="110">
            <template slot-scope="scope">
              {{ scope.row.subtitle }}
            </template>
          </el-table-column>
          <el-table-column label="图片" width="110">
            <template slot-scope="scope">
              <img
                v-if="scope.row.url"
                :src="scope.row.url"
                alt=""
                style="width: 60px; height: 60px; object-fit: cover;"
              />
            </template>
          </el-table-column>
          <el-table-column label="零售价" width="110">
            <template slot-scope="scope">
              {{ scope.row.price }}
            </template>
          </el-table-column>
          <el-table-column label="抵扣价" width="110">
            <template slot-scope="scope">
              {{ scope.row.offsettingPrice }}
            </template>
          </el-table-column>
          <el-table-column label="进货价" width="110">
            <template slot-scope="scope">
              {{ scope.row.purchasePrice }}
            </template>
          </el-table-column>
          <el-table-column label="预估收益" width="110">
            <template slot-scope="scope">
              {{ scope.row.estimatedRevenue }}
            </template>
          </el-table-column>
          <el-table-column label="是否上架" width="110">
            <template slot-scope="scope">
              <el-switch
                style="vertical-align: sub"
                v-model="scope.row.shelvesStatus"
                active-value="1"
                inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="skuSwitchChange(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-update"
                style="margin: 0"
                @click="getSku(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="text"
                icon="el-icon-delete"
                style="margin: 0"
                @click="delSku(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="用户真实评论" v-if="$route.query.id">
        <el-table ref="mytable" :data="table_data1" style="width: 100%">
          <el-table-column
            align="center"
            v-for="(item, index, key) in table_columns"
            :item="item"
            :key="key"
            :index="index"
            :label="item.label"
          >
            <template slot-scope="scope">
              <span
                v-if="item.prop !== 'score' && item.prop !== 'createTime'"
                >{{ scope.row[item.prop] }}</span
              >
              <span v-else-if="item.prop === 'score'">{{
                scope.row[item.prop] === 1 ? "地雷" : "好货"
              }}</span>
              <span v-else>{{ formatDateTime(scope.row[item.prop]) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)"
                type="primary"
                >Edit</el-button
              >

              <el-button
                size="mini"
                :plain="true"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
                >Delete</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="手动添加评论" v-if="$route.query.id">
        <el-button size="mini" @click="handleAdd()" type="primary"
          >添加</el-button
        >
        <el-table ref="mytable" :data="table_data" style="width: 100%">
          <el-table-column
            align="center"
            v-for="(item, index, key) in table_columns"
            :item="item"
            :key="key"
            :index="index"
            :label="item.label"
          >
            <template slot-scope="scope">
              <span
                v-if="item.prop !== 'score' && item.prop !== 'createTime'"
                >{{ scope.row[item.prop] }}</span
              >
              <span v-else-if="item.prop === 'score'">{{
                scope.row[item.prop] === 1 ? "地雷" : "好货"
              }}</span>
              <span v-else>{{ formatDateTime(scope.row[item.prop]) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)"
                type="primary"
                >Edit</el-button
              >

              <el-button
                size="mini"
                :plain="true"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
                >Delete</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="info" icon="el-icon-back" @click="backPage"
          >返回商品列表</el-button
        >
        <el-button type="primary" @click="updateSpu">发布商品</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="添加/修改评论" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="客户id" :label-width="formLabelWidth">
          <el-input v-model="form.customerId" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户姓名" :label-width="formLabelWidth">
          <el-input
            v-model="form.customerName"
            disabled
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="评论内容" :label-width="formLabelWidth">
          <el-input v-model="form.comment" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="好货/地雷" :label-width="formLabelWidth">
          <el-select v-model="form.score" placeholder="请选择">
            <el-option label="地雷" :value="1"></el-option>
            <el-option label="好货" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="评论时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form.createTime"
            type="datetime"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="排序" :label-width="formLabelWidth">
          <el-input v-model="form.weight" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateComment">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="添加/修改规格" :visible.sync="skuTableDialog">
      <el-form :model="skuForm">
        <el-form-item label="型号" :label-width="formLabelWidth">
          <el-input v-model="skuForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="颜色" :label-width="formLabelWidth">
          <el-input v-model="skuForm.subtitle" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图片" :label-width="formLabelWidth">
          <el-upload
            accept=",.JPG,.jpeg,.png,.gif,.ico,.JPEG,.PNG,.GIF,.ICO,.jpg"
            :action="uploadApi"
            :headers="headers"
            name="image"
            :on-success="uploadSkuSuccess"
            class="avatar-uploader"
            :show-file-list="false"
          >
            <img v-if="skuForm.url" :src="skuForm.url" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="零售价" :label-width="formLabelWidth">
          <el-input v-model="skuForm.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="抵扣价" :label-width="formLabelWidth">
          <el-input
            v-model="skuForm.offsettingPrice"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="进货价" :label-width="formLabelWidth">
          <el-input
            v-model="skuForm.purchasePrice"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="预估收益" :label-width="formLabelWidth">
          <el-input
            v-model="skuForm.estimatedRevenue"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否上架" :label-width="formLabelWidth">
          <el-select v-model="skuForm.shelvesStatus" placeholder="请选择">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="skuTableDialog = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateSku">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Tinymce from "@/components/Tinymce";
import { formatDate } from "@/utils/index";
import {
  queryTypeDetail,
  querySpuById,
  queryAllBrands,
  queryAllLogisticsTemplates,
  queryAllLevels,
  queryAllServiceSupport,
  updateSpu,
  queryComment
} from "@/api/goods/updatespu";
import { addSpu } from "@/api/goods/addspu";
import {
  listComment,
  getComment,
  delComment,
  addComment,
  updateComment,
  exportComment
} from "@/api/goods/comment";
import { listSku, getSku, delSku, addSku, updateSku } from "@/api/goods/sku";
import { getToken } from "@/utils/auth";
import { priceValidator, isMoney, isDigits, integer } from "@/utils/validate";

export default {
  components: { Tinymce },
  data() {
    return {
      commentType: "add",
      dialogFormVisible: false,
      formLabelWidth: "120px",
      form: {},
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      allSpecValues: [], // 所有的规格值
      selectedSpecValueIds: [], //选择的规格值id
      specs: [], // 规格信息
      oldSpuSpecValues: [], // 老的规格信息
      isProcess: false, // 接口是否处理中
      batchWeight: "", // 批量填充的重量
      batchPrice: "", // 批量填充的价格
      batchStock: "", // 批量填充的库存
      editSku: {
        name: "",
        remark: "",
        subtitle: "",
        skuImages: [],
        warningStock: "",
        isBatchSku: "0",
        skuBatchList: new Array()
      },
      editSkuShow: false, // 编辑商品显示标记
      currentSku: {}, // 当前选中的sku信息
      // skus: [], // 单品信息
      selectedAttributeValueIds: [], // 选中的属性值数组
      uploadApi: process.env.VUE_APP_BASE_API + "/aliyun/oss/uploadToAliOss",
      uploadVideoApi:
        process.env.VUE_APP_BASE_API +
        "/aliyun/oss/uploadToAliOss" +
        "?name=video&type=1", // 上传视频api
      headers: {
        Authorization: "Bearer " + getToken()
      },
      imageDialogVisible: false, // 图片放大
      dialogImageUrl: "", // 放大图片的地址
      videoPics: [], // 视频封面图片
      videos: [], // 视频图片
      serviceSupportChecked: [], // 选中的服务支持
      attributes: [], // 商品属性
      cateNames: "", // 已选分类的名称
      brands: [], // 品牌
      serviceSupports: [],
      spu: {
        brandId: "",
        id: "",
        mobileDesc: "",
        name: "",
        subtitle: "",
        price: "",
        isVirtual: "",
        shelvesStatus: "",
        skus: [],
        spuAttributeValues: [],
        spuImages: [],
        serviceSupport: [],
        spuSpecValues: [],
        videoPic: "",
        video: "",
        logisticsTemplateId: "",
        radio: "1",
        goodsRealSold: "",
        goodsSold: "",
        approvalRealRating: "",
        approvalRating: "",
        url: [],
        topUrl: [],
        detailsUrl: [],
        evaluationFlag: [],
        offsettingPrice: "",
        purchasePrice: "",
        estimatedRevenue: "",
        goodsStatus: "1"
      },
      customerLevels: [],
      logisticsTemplates: [],
      rules: {
        name: [
          {
            required: true,
            message: "请输入商品标题",
            trigger: "blur"
          }
        ],
        price: [
          {
            required: true,
            trigger: "blur",
            validator: priceValidator
          }
        ],
        brandId: [
          {
            required: true,
            message: "请选择商品品牌",
            trigger: "blur"
          }
        ],
        url: [
          {
            required: true,
            message: "请上传主图",
            trigger: "blur"
          }
        ],
        topUrl: [
          {
            required: true,
            message: "请上传顶部图",
            trigger: "blur"
          }
        ],
        detailsUrl: [
          {
            required: true,
            message: "请上传详情页图",
            trigger: "blur"
          }
        ],
        logisticsTemplateId: [
          {
            required: true,
            message: "请选择物流模板",
            trigger: "blur"
          }
        ]
      },
      new_date_json: {},
      multipleSelection: [],
      is_edit: true, //是否可编辑
      is_delete: true, //是否可删除
      selection: true, //是否需要复选框
      radio: false, //单选变色
      space_color: true, //隔行变色
      table_columns: [
        {
          prop: "customerImage",
          label: "用户头像",
          width: "150"
        },
        {
          prop: "customerName",
          label: "用户姓名",
          width: "150"
        },
        {
          prop: "comment",
          label: "评论内容",
          width: "150"
        },
        {
          prop: "score",
          label: "好货/地雷",
          width: ""
        },
        {
          prop: "commentPics",
          label: "买家秀",
          width: "150"
        },
        {
          prop: "createTime",
          label: "评论时间",
          width: "150"
        },
        {
          prop: "weight",
          label: "排序",
          width: "150"
        }
      ],
      table_data1: [],
      table_data: [],
      spuId: this.$route.query.id,
      queryParams: {
        spuId: undefined,
        storeId: undefined
      },
      skuData: [],
      skuForm: {},
      skuTableDialog: false,
      skuType: "add"
    };
  },
  created() {
    if (this.spuId) {
      this.querySpu();
    } else {
      this.queryAllServiceSupport();
    }
    this.queryLogisticsTemplates();
  },
  mounted: function() {
    this.initEditAttribute();
    this.$nextTick(function() {
      this.tableRowClassName();
    });
  },
  computed: {
    formatDateTime() {
      return function(date) {
        return formatDate(date, "yyyy-MM-dd hh:mm:ss");
      };
    }
  },
  watch: {
    space_color: function() {
      this.$nextTick(function() {
        this.tableRowClassName();
      });
    },
    table_data: function() {
      this.$nextTick(function() {
        this.tableRowClassName();
      });
    },
    table_data1: function() {
      this.$nextTick(function() {
        this.tableRowClassName();
      });
    }
  },
  methods: {
    //隔行变色
    tableRowClassName() {
      var trs = this.$refs.mytable.$el
        .getElementsByTagName("tbody")[0]
        .getElementsByTagName("tr");
      for (var i in trs) {
        if (i % 2 == 0) {
          //当隔行变色未true时改变颜色
          if (this.space_color) {
            trs[i].style.backgroundColor = "#f0f9eb";
          } else {
            trs[i].style.backgroundColor = "";
          }
        }
      }
    },
    skuSwitchChange(row) {
      this.skuForm = row;
      updateSku(this.skuForm).then(response => {
        if (response.code === 200) {
          this.msgSuccess("修改成功");
          listSku(this.queryParams).then(response => {
            this.skuData = response.rows;
          });
        }
      });
    },
    addOrUpdateSku() {
      switch (this.skuType) {
        case "add":
          this.skuForm.spuId = this.spuId;
          addSku(this.skuForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess("修改成功");
              listSku(this.queryParams).then(response => {
                this.skuData = response.rows;
              });
              this.skuTableDialog = false;
            }
          });
          break;

        case "update":
          updateSku(this.skuForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess("修改成功");
              listSku(this.queryParams).then(response => {
                this.skuData = response.rows;
              });
              this.skuTableDialog = false;
            }
          });
          break;
      }
    },
    getSku(row) {
      this.skuType = "update";
      getSku(row.id).then(response => {
        this.skuForm = response.data;
        this.skuTableDialog = true;
      });
    },
    addOrUpdateComment() {
      switch (this.commentType) {
        case "add":
          let formData = {
            comment: this.form.comment,
            createTime: this.form.createTime,
            customerId: this.form.customerId,
            customerImage: undefined,
            customerName: this.form.customerName,
            isTrue: "1",
            score: this.form.score,
            spuId: this.spuId,
            weight: this.form.weight
          };
          addComment(formData).then(response => {
            if (response.code === 200) {
              this.msgSuccess("新增成功");
              this.dialogFormVisible = false;
              this.initEditAttribute();
            }
          });
          break;
        case "update":
          updateComment(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess("修改成功");
              this.dialogFormVisible = false;
              this.initEditAttribute();
            }
          });
          break;
      }
    },
    handleEdit(index, row) {
      this.commentType = "update";
      const id = row.id;
      getComment(id).then(response => {
        this.form = response.data;
        this.dialogFormVisible = true;
      });
    },
    handleDelete(index, row) {
      this.$confirm("是否确认删除", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delComment(row.id);
        })
        .then(() => {
          this.initEditAttribute();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },
    handleSave(index, row, type) {
      row.edit = false;
      delete this.table_data[index].add;
      this.$message({
        message: "保存成功！",
        type: "success"
      });
    },
    handleAdd() {
      this.commentType = "add";
      this.dialogFormVisible = true;
    },
    //初始化编辑属性
    initEditAttribute() {
      queryComment({
        spuId: this.spuId,
        isTrue: "1"
      }).then(res => {
        this.table_data = res.data;
      });
      queryComment({
        spuId: this.spuId,
        isTrue: "0"
      }).then(res => {
        this.table_data1 = res.data;
      });
    },
    handleRemove(file) {
      console.log(file);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 查询所有的物流模版
    queryLogisticsTemplates() {
      queryAllLogisticsTemplates().then(res => {
        this.logisticsTemplates = res;
      });
    },
    // 查询商品信息
    querySpu() {
      querySpuById(this.spuId).then(res => {
        if (res) {
          this.queryParams.storeId = res.storeId;
          this.queryParams.spuId = this.spuId;
          listSku(this.queryParams).then(response => {
            this.skuData = response.rows;
          });
          this.cateNames =
            res.firstCategory.name +
            "/" +
            res.secondCategory.name +
            "/" +
            res.thirdCategory.name;
          this.spu.id = res.id;
          this.spu.mobileDesc = res.mobileDesc;
          this.spu.name = res.name;
          this.spu.price = res.price;
          this.spu.shelvesStatus = res.shelvesStatus;
          this.spu.subtitle = res.subtitle;
          this.oldSpuSpecValues = res.spuSpecValues;
          this.spu.isVirtual = res.isVirtual;
          this.spu.videoPic = res.videoPic;
          this.spu.video = res.video;
          this.spu.logisticsTemplateId = res.logisticsTemplateId;
          this.spu.goodsRealSold = res.goodsRealSold || 0;
          this.spu.goodsSold = res.goodsSold || 0;
          this.spu.approvalRealRating = res.approvalRealRating || 0;
          this.spu.approvalRating = res.approvalRating || 0;
          this.spu.offsettingPrice = res.offsettingPrice;
          this.spu.purchasePrice = res.purchasePrice;
          this.spu.estimatedRevenue = res.estimatedRevenue;
          this.spu.goodsStatus = res.goodsStatus;
          this.spu.evaluationFlag = res.evaluationFlag.split(",");
          if (res.video) {
            this.videos = [{ name: res.video, url: res.video }];
          }
          if (res.videoPic) {
            this.videoPics = [{ name: res.videoPic, url: res.videoPic }];
          }
          this.spu.url = [{ url: res.url }];
          this.spu.topUrl = [{ url: res.topUrl }];
          this.spu.detailsUrl = [{ url: res.detailsUrl }];

          res.spuSpecValues.forEach(spec => {
            if (this.specs.filter(s => s.specId == spec.specId).length == 0) {
              spec.spec.specValues.forEach(value => {
                this.allSpecValues.push(value);
              });
              this.specs.push(spec);
              this.selectedSpecValueIds.push(spec.spec.specValues[0].id);
            }
          });

          this.queryType(res.typeId, res.spuAttributeValues);
          this.queryAllBrands(res.brandId);
          this.queryAllServiceSupport(res.serviceSupport.split(","));
        }
      });
    },
    // 加载商品类型
    queryType(typeId, spuAttributeValues) {
      queryTypeDetail(typeId).then(res => {
        if (res) {
          this.attributes = res.attributes;
          if (spuAttributeValues && spuAttributeValues.length > 0) {
            spuAttributeValues.forEach(attribute => {
              this.selectedAttributeValueIds.push(attribute.attributeValueId);
            });
          }
        }
      });
    },
    // 查询所有的品牌
    queryAllBrands(brandId) {
      queryAllBrands().then(res => {
        this.brands = res;
        this.spu.brandId = brandId;
      });
    },
    // 查询所有服务支持
    queryAllServiceSupport(serviceSupport) {
      console.log(serviceSupport);
      queryAllServiceSupport().then(res => {
        this.serviceSupports = res;
        if (serviceSupport) {
          this.serviceSupportChecked = serviceSupport.map(item => {
            return Number(item);
          });
        }
      });
    },
    // 上传商品图片
    uploadSkuSuccess(res) {
      this.skuForm.url = res;
    },
    uploadSpuPicSuccess1(res) {
      this.spu.url = [{ url: res }];
    },
    uploadSpuPicSuccess2(res) {
      this.spu.topUrl = [{ url: res }];
    },
    uploadSpuPicSuccess3(res) {
      this.spu.detailsUrl = [{ url: res }];
    },
    // 删除图片
    removeSpuPic1(file) {
      this.spu.url = [];
    },
    removeSpuPic2(file) {
      this.spu.topUrl = [];
    },
    removeSpuPic3(file) {
      this.spu.detailsUrl = [];
    },
    delSku(row) {
      this.$confirm("是否确认删除", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delSku(row.id);
        })
        .then(() => {
          listSku(this.queryParams).then(response => {
            this.skuData = response.rows;
          });
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },
    updateSpu() {
      let formData = {
        brandId: this.spu.brandId,
        id: this.spu.id || undefined,
        mobileDesc: this.spu.mobileDesc,
        name: this.spu.name,
        subtitle: this.spu.subtitle,
        price: this.spu.price,
        isVirtual: this.spu.isVirtual,
        shelvesStatus: this.spu.shelvesStatus,
        spuAttributeValues: this.spu.spuAttributeValues,
        spuImages: this.spu.spuImages,
        serviceSupport: this.spu.serviceSupport,
        spuSpecValues: this.spu.spuSpecValues,
        videoPic: this.spu.videoPic,
        video: this.spu.video,
        logisticsTemplateId: this.spu.logisticsTemplateId,
        radio: this.spu.radio,
        goodsRealSold: this.spu.goodsRealSold,
        goodsSold: this.spu.goodsSold,
        approvalRealRating: this.spu.approvalRealRating,
        approvalRating: this.spu.approvalRating,
        url: this.spu.url,
        topUrl: this.spu.topUrl,
        detailsUrl: this.spu.detailsUrl,
        evaluationFlag: this.spu.evaluationFlag,
        offsettingPrice: this.spu.offsettingPrice,
        purchasePrice: this.spu.purchasePrice,
        estimatedRevenue: this.spu.estimatedRevenue,
        goodsStatus: this.spu.goodsStatus,
        video: (this.videos[0] && this.videos[0].url) || ""
      };
      formData.evaluationFlag =
        this.spu.evaluationFlag.length > 0
          ? this.spu.evaluationFlag.join(",")
          : "";
      formData.serviceSupport =
        this.serviceSupportChecked.length > 0
          ? this.serviceSupportChecked.join(",")
          : "";
      formData.url = this.spu.url[0].url || "";
      formData.topUrl = this.spu.topUrl[0].url || "";
      formData.detailsUrl = this.spu.detailsUrl[0].url || "";
      this.$refs["form"].validate(valid => {
        if (!this.isProcess && valid) {
          this.isProcess = true;
          if (this.spuId) {
            updateSpu(formData).then(res => {
              this.isProcess = false;
              this.$message({
                type: "success",
                message: "修改成功!"
              });
              this.$router.push({ path: "/goods/goodsManager/goods" });
            });
          } else {
            addSpu(formData).then(res => {
              this.isProcess = false;
              this.$message({
                type: "success",
                message: "添加成功!"
              });
              this.$router.push({ path: "/goods/goodsManager/goods" });
            });
          }
        }
      });
    },
    backPage() {
      this.$router.back(-1);
    },
    // 上传视频成功
    uploadVideoSuccess(res) {
      this.videos = [{ name: res, url: res }];
    },
    // 删除视频
    removeVideo(file) {
      if (file && file.status === "success") {
        this.videos = [];
      }
    },
    // 视频上传前判断是否已经有视频如果有视频则提示只能上传一张
    videoBeforeUpload() {
      if (this.videos && this.videos.length > 0) {
        this.$message({
          type: "error",
          message: "只能上传一个视频!"
        });
        return false;
      }
      return true;
    }
  }
};
</script>
<style lang="less" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
.productSmallImage {
  /deep/.el-upload--picture-card {
    width: 60px;
    height: 60px;
    line-height: 58px;
    i {
      line-height: unset;
    }
  }
  /deep/.el-upload-list--picture-card {
    .el-upload-list__item {
      width: 60px;
      height: 60px;
    }
    .el-upload-list__item-thumbnail {
      height: 60px;
      object-fit: cover;
    }
  }
}
</style>
